<template>
  <div class="page-user-login">
    <van-nav-bar
      left-arrow
      @click-left="$router.back()"
      title="登录"
    ></van-nav-bar>
    <!-- 登录提交表单 -->
    <van-form @submit="onSubmit">
      <van-field
        v-model="form.mobile"
        name="mobile"
        label="手机号"
        placeholder="手机号"
        :rules="[
          { required: true, message: '请填写手机号' },
          { pattern, message: '请填写正确格式的手机号!' },
        ]"
      />
      <van-field
        v-model="form.code"
        type="password"
        name="code"
        label="验证码"
        placeholder="密码"
        :rules="[
          { required: true, message: '请填写验证码' },
          { validator, message: '请输入正确的6位验证码' },
        ]"
      >
        <template #button>
          <van-button native-type="button" type="primary" round
            >发送验证码</van-button
          >
        </template>
      </van-field>
      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit"
          >登录</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { mapActions } from 'vuex' // 从vuex中导入
export default {
  name: 'user-chat',
  data () {
    return {
      // 技巧：变量名和后台接口需要的参数保持一致
      form: {
        mobile: '15801018888',
        code: '246810'
      },
      pattern: /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/
    }
  },
  methods: {
    ...mapActions(['getToken']),
    validator (val) {
      if (val.length !== 6) return false
      return true
    },
    async onSubmit (values) {
      console.log('submit', values)
      try { // try catch 捕获异常  try 里面放正常代码
        // 提交表单发送登录请求===>actions里面的方法是异步的
        await this.getToken(values) // await等到发送请求之后再执行后面的同步代买: 提示框和跳转路由
        // 请求成功提示弹窗
        this.$toast.success('登录成功')
        // 登录跳转路由 ===> 前置守卫
        this.$router.push(this.$route.query.redirect || '/')
      } catch (error) { // 捕获请求错误
        // console.log('登录请求错误', error.message)
        this.$toast.fail(error.message)
      }
    }
  }
}
</script>

<style scoped lang='less'></style>
